// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/2/23 02:24
// 文件名称 ：   main.go
// 工程名称 ：   videostream
// 开发工具 ：   GoLand
//

package main

import (
	"github.com/julienschmidt/httprouter"
	"net/http"
)

type MiddleWareHandler struct {
	r *httprouter.Router
	l *ConnLimiter
}

func NewMiddleWareHandler(r *httprouter.Router, cc int) *MiddleWareHandler {
	m := new(MiddleWareHandler)
	m.r = r
	m.l = NewConnLimiter(cc)
	return m
}

func (mh *MiddleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 添加一些验证信息
	if !mh.l.GetConn() {
		sendErrorResponse(w, http.StatusTooManyRequests, "Too many requests")
		return
	}
	defer mh.l.RealseConn()
	mh.r.ServeHTTP(w, r)
}

func RegisterHandlers() *httprouter.Router {
	router := httprouter.New()
	router.GET("/videos/:vid", streamHandler)
	router.POST("/upload/:vid", uploadHandler)
	return router
}

func main() {
	r := RegisterHandlers()
	limitCount := 2
	mh := NewMiddleWareHandler(r, limitCount)
	err := http.ListenAndServe(":9000", mh)
	if err != nil {
		panic(err)
	}
}
